from typing import Annotated
from fastapi import Body, FastAPI, BackgroundTasks, Depends
from fastapi.concurrency import run_in_threadpool
import time
from pydantic import BaseModel
import uvicorn
import threading
import os


app = FastAPI()


def sleep(t):
    print("sleep", threading.current_thread().name)
    time.sleep(t)


@app.get("/index1")
async def index1():
    print(os.getpid())
    print("index1", threading.current_thread().name)
    # time.sleep(10)
    # sleep(5)
    await run_in_threadpool(sleep, 5)
    # await asyncio.sleep(10)
    return {"value": "index1"}


@app.get("/index2")
async def index2():
    print(os.getpid())
    print("index2", threading.current_thread().name)
    return {"value": "index2"}


@app.get("/index3")
def index3():
    print(os.getpid())
    print("index3", threading.current_thread().name)
    time.sleep(5)
    return {"value": "index3"}


class Payload(BaseModel):
    value: str


@app.post("/post")
def post(payload: Payload, background: BackgroundTasks):
    def _bg_task():
        raise Exception("123")
        print(payload.value)

    background.add_task(_bg_task)
    return payload


@app.post("/patch")
def patch(refine_type: Annotated[str, Body(embed=True)]):
    print(refine_type)
    return {"value": "patch"}


if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8080)
